package com.chen.api;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chen.entity.AccountA;
import com.chen.exception.MyRpcException;
import com.chen.service.AccountAService;
import org.dromara.hmily.annotation.HmilyTCC;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

public class AccountADubboServiceImpl implements IAccountADubboService {
    @Autowired
    private AccountAService accountAService;

    @Override
    public com.chen.dto.AccountA findAccountAByUserId(int userId) {
        LambdaQueryWrapper<com.chen.entity.AccountA> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(com.chen.entity.AccountA::getUserId,userId);
        AccountA accountA = accountAService.getOne(queryWrapper);
        com.chen.dto.AccountA accountADto = new com.chen.dto.AccountA();
        BeanUtils.copyProperties(accountA,accountADto);
        return accountADto;
    }


    /**
     * 账户A用1美元兑换7人民币
     * @param userId
     * @param dollarAmount
     * @throws MyRpcException
     */
    @Override
    @HmilyTCC(confirmMethod = "confirmDollarToRmb",cancelMethod = "cancelDollarToRmb")
    @Transactional(rollbackFor = Exception.class)
    public void dollarToRmb(int userId, BigDecimal dollarAmount) throws MyRpcException {
        //准备
        AccountA accountA = accountAService.findAccountByUserId(userId);
        if (accountA == null){
            throw new MyRpcException("账户A不存在");
        }
        if (accountA.getDollar().compareTo(dollarAmount) == -1){
            throw new MyRpcException("转出美元不能超过账户美元余额");
        }
        //冻结金额
        int rows = accountAService.frozenDollarAmount(userId, dollarAmount);
        if (rows != 1){
            throw new MyRpcException("资金冻结异常");
        }

    }

    @Transactional(rollbackFor = Exception.class)
    public void confirmDollarToRmb(int userId, BigDecimal dollarAmount) throws MyRpcException{
        //确认转换
        accountAService.commitDollarToRmb(userId,dollarAmount);
    }

    @Transactional(rollbackFor = Exception.class)
    public void cancelDollarToRmb(int userId, BigDecimal dollarAmount) throws MyRpcException{
        //取消转换
        accountAService.cancelDollarToRmb(userId,dollarAmount);
    }

}
